const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
// const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const { koaBody } = require('koa-body')
const path = require('path')
const koastatic = require('koa-static')
const cors = require('koa2-cors')
const connectDB = require('./config/database')

const index = require('./routes/index')
const users = require('./routes/users')
const upload = require('./routes/upload')
const administration = require('./routes/admin/admin')
const admindetail = require('./routes/admin/admin')
const jobList = require('./routes/job/job')
const jobdetail = require('./routes/job/job')
const testbank = require('./routes/testbank/testbank')
const testadmindetail = require('./routes/testbank/testbank')
const about = require('./routes/about/about')
const explainlist = require('./routes/explain/explain')
const explaindetail = require('./routes/explain/explain')
const swipper = require('./routes/home/swipper/swipper')
const testanswer=require('./routes/testbank/testbank')

// error handler
onerror(app)
app.use(cors())
connectDB()

//! 注意的是通常静态服务都是在最前面
app.use(koastatic(path.join(__dirname, '/public')))

// middlewares
// app.use(
//   bodyparser({
//     enableTypes: ['json', 'form', 'text'],
//   }),
// )
app.use(json())
app.use(logger())

app.use(
  views(__dirname + '/views', {
    extension: 'pug',
  }),
)

app.use(koastatic(path.join(__dirname, 'public'))) //这个public以下的路径就是生成的url。

//图片
app.use(
  koaBody({
    multipart: true,
    formidable: {
      maxFileSize: 200 * 1024 * 1024,
      uploadDir: path.join(__dirname, '/public/upload'),
      // 上传目录，意思是说上传到当前项目的/public/upload目录下/ 是否保留拓展名
      keepExtensions: true,
    },
  }),
)

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

//路由

// routes  administration
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(upload.routes(), upload.allowedMethods())
app.use(administration.routes(), administration.allowedMethods())
app.use(admindetail.routes(), admindetail.allowedMethods())
app.use(jobList.routes(), jobList.allowedMethods())
app.use(jobdetail.routes(), jobdetail.allowedMethods())
app.use(testbank.routes(), testbank.allowedMethods())
app.use(testadmindetail.routes(), testadmindetail.allowedMethods())
app.use(about.routes(), about.allowedMethods())
app.use(explainlist.routes(), explainlist.allowedMethods())
app.use(explaindetail.routes(), explaindetail.allowedMethods())
app.use(swipper.routes(), swipper.allowedMethods())
app.use(testanswer.routes(),testanswer.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
